package com.css.zfzx.fxpg.modules.preestimate.workspace.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.common.utils.VectorDataUtil;
import com.css.zfzx.fxpg.modules.preestimate.workspace.repository.FxPreestimateWorkspaceNativeRepository;
import com.css.zfzx.fxpg.modules.preestimate.workspace.repository.FxPreestimateWorkspaceRepository;
import com.css.zfzx.fxpg.modules.preestimate.workspace.repository.entity.FxPreestimateWorkspaceEntity;
import com.css.zfzx.fxpg.modules.preestimate.workspace.service.FxPreestimateWorkspaceService;
import com.css.zfzx.fxpg.modules.preestimate.workspace.viewobjects.FxPreestimateWorkspaceQueryParams;
import com.css.zfzx.fxpg.modules.preestimate.workspace.viewobjects.FxPreestimateWorkspaceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author andy
 * @date 2020-11-19
 */
@Service
@Slf4j
public class FxPreestimateWorkspaceServiceImpl implements FxPreestimateWorkspaceService {
    @Value("${file.upload.path}")
    private String uploadPath;
    @Autowired
    private FxPreestimateWorkspaceRepository fxPreestimateWorkspaceRepository;
    @Autowired
    private FxPreestimateWorkspaceNativeRepository fxPreestimateWorkspaceNativeRepository;

    @Override
    public JSONObject queryFxPreestimateWorkspaces(FxPreestimateWorkspaceQueryParams queryParams, int curPage, int pageSize) {
        Page<FxPreestimateWorkspaceEntity> fxPreestimateWorkspacePage = this.fxPreestimateWorkspaceNativeRepository.queryFxPreestimateWorkspaces(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxPreestimateWorkspacePage);
        return jsonObject;
    }


    @Override
    public FxPreestimateWorkspaceEntity getFxPreestimateWorkspace(String id) {
        FxPreestimateWorkspaceEntity fxPreestimateWorkspace = this.fxPreestimateWorkspaceRepository.findById(id).orElse(null);
        return fxPreestimateWorkspace;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxPreestimateWorkspaceEntity saveFxPreestimateWorkspace(FxPreestimateWorkspaceEntity fxPreestimateWorkspace) {
        String uuid = UUIDGenerator.getUUID();
        fxPreestimateWorkspace.setId(uuid);
        fxPreestimateWorkspace.setCreateUser(PlatformSessionUtils.getUserId());
        fxPreestimateWorkspace.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxPreestimateWorkspaceRepository.save(fxPreestimateWorkspace);
        return fxPreestimateWorkspace;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxPreestimateWorkspaceEntity updateFxPreestimateWorkspace(FxPreestimateWorkspaceEntity fxPreestimateWorkspace) {
        fxPreestimateWorkspace.setUpdateUser(PlatformSessionUtils.getUserId());
        fxPreestimateWorkspace.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxPreestimateWorkspace.getId();
        FxPreestimateWorkspaceEntity one = fxPreestimateWorkspaceRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxPreestimateWorkspace, one);
        this.fxPreestimateWorkspaceRepository.save(one);
        return fxPreestimateWorkspace;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxPreestimateWorkspaces(List<String> ids) {
        List<FxPreestimateWorkspaceEntity> fxPreestimateWorkspaceList = this.fxPreestimateWorkspaceRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxPreestimateWorkspaceList) && fxPreestimateWorkspaceList.size() > 0) {
            for (FxPreestimateWorkspaceEntity fxPreestimateWorkspace : fxPreestimateWorkspaceList) {
                this.fxPreestimateWorkspaceRepository.delete(fxPreestimateWorkspace);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public List<FxPreestimateWorkspaceEntity> getFxPreestimateWorkspaces(FxPreestimateWorkspaceQueryParams queryParams) {
        List<FxPreestimateWorkspaceEntity> fxPreestimateWorkspaces = this.fxPreestimateWorkspaceNativeRepository.listFxPreestimateWorkspaces(queryParams);
        return fxPreestimateWorkspaces;
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置解析从第1+1+1行开始
            params.setTitleRows(1);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxPreestimateWorkspaceVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxPreestimateWorkspaceVO.class, params);
            List<FxPreestimateWorkspaceVO> list = result.getList();
            // 批量新增
            this.saveData(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxPreestimateWorkspaceVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxPreestimateWorkspaceVO workspaceVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + workspaceVO.getRowNum() + "行" + workspaceVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    private void saveData(List<FxPreestimateWorkspaceVO> list) {
        for (int i = 0; i < list.size(); i++) {
            FxPreestimateWorkspaceEntity workspaceEntity = new FxPreestimateWorkspaceEntity();
            FxPreestimateWorkspaceVO workspaceVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(workspaceVO, workspaceEntity);
            workspaceEntity.setIsValid("1");
            saveOrUpdate(workspaceEntity);
        }
    }

    /**
     * 保存或者修改（OBJECTID字段值相同的数据只能有一条数据）
     *
     * @param workspaceEntity
     */
    @Override
    public void saveOrUpdate(FxPreestimateWorkspaceEntity workspaceEntity) {
        FxPreestimateWorkspaceQueryParams queryParams = new FxPreestimateWorkspaceQueryParams();
        queryParams.setOBJECTID(workspaceEntity.getObjectid());
        List<FxPreestimateWorkspaceEntity> workspaceEntities = fxPreestimateWorkspaceNativeRepository.listFxPreestimateWorkspaces(queryParams);
        // 若查到数据为空，则新增
        if (CollectionUtils.isEmpty(workspaceEntities)) {
            this.saveFxPreestimateWorkspace(workspaceEntity);
        } else {
            if (workspaceEntities.size() == 1) {
                FxPreestimateWorkspaceEntity sourceProvinceEntity = workspaceEntities.get(0);
                BeanUtil.copyPropertiesIgnoreNull(workspaceEntity, sourceProvinceEntity);
                this.updateFxPreestimateWorkspace(sourceProvinceEntity);
            } else {
                throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
            }
        }
    }

    @Override
    public String exportExcel(FxPreestimateWorkspaceQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxPreestimateWorkspaceEntity> workspaceEntities = fxPreestimateWorkspaceNativeRepository.listFxPreestimateWorkspaces(queryParams);
            // 深拷贝
            ArrayList<FxPreestimateWorkspaceVO> vos = new ArrayList<>();
            for (FxPreestimateWorkspaceEntity workspaceEntity : workspaceEntities) {
                FxPreestimateWorkspaceVO vo = new FxPreestimateWorkspaceVO();
                BeanUtils.copyProperties(workspaceEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "预评估工作区数据", "预评估工作区数据", FxPreestimateWorkspaceVO.class, "预评估工作区数据.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }


    @Override
    public String importSHPFile(File file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            List<FxPreestimateWorkspaceVO> workspaceVOs = new ArrayList<FxPreestimateWorkspaceVO>();
            List<List<Object>> list = VectorDataUtil.readSHPFile2(file);
            for (int i = 0; i < list.size(); i++) {
                List<Object> values = list.get(i);
                FxPreestimateWorkspaceVO workspaceVO = new FxPreestimateWorkspaceVO();
                workspaceVO.setCoordinates(values.get(0).toString());
                workspaceVO.setObjectid(Integer.parseInt(values.get(1).toString()));
                //workspaceVO.setId(values.get(2).toString());
                workspaceVO.setName(values.get(3).toString());
                workspaceVO.setTime(values.get(4).toString());
                workspaceVO.setWxqgk(values.get(5).toString());
                workspaceVO.setCsdzzh(values.get(6).toString());
                workspaceVO.setYjczyd(values.get(7).toString());
                workspaceVO.setAllreport(values.get(8).toString());
                workspaceVO.setShapeLeng(Double.parseDouble(values.get(9).toString()));
                workspaceVO.setShapeArea(values.get(10).toString());
                workspaceVOs.add(workspaceVO);
            }
            // 批量新增
            this.saveData(workspaceVOs);
            returnMsg.append("成功导入" + workspaceVOs.size() + "条.");
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }


    @Override
    public String importSHP(MultipartFile[] files) {
        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();
        //数据校验
        if (files == null || files.length < 1) {
            return returnMsg.append("上传失败，请选择文件").toString();
        }
        String fileName = null;
        for (MultipartFile file : files) {
            String oldFileName = file.getOriginalFilename();
            String substring = oldFileName.substring(oldFileName.lastIndexOf("."));
            if(".shp".equals(substring)){
                fileName=oldFileName;
            }
            File savefile = new File(uploadPath + oldFileName);
            if (!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }
            try {
                file.transferTo(savefile);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                return "上传文件失败，失败信息：" + e.getMessage();
            }
        }
        try {
            List<FxPreestimateWorkspaceVO> workspaceVOs = new ArrayList<FxPreestimateWorkspaceVO>();
            List<List<Object>> list = VectorDataUtil.readSHPFile(uploadPath+fileName, "UTF-8");
            //List<List<Object>> list = VectorDataUtil.readSHPFile("E:\\IdeaProjects\\zfzx文档\\风险评估\\预评估\\预评估工作区范围样例数据-矢量数据\\甘青川地震危险区.shp");
            int err = 0;
            for (int i = 0; i < list.size(); i++) {
                List<Object> values = list.get(i);
                if (CollectionUtils.isEmpty(values) || values.size() < 11) {
                    err++;
                    returnMsg.append("文件解析后数据格式不符：" + err + "条,");
                    continue;
                }
                FxPreestimateWorkspaceVO workspaceVO = new FxPreestimateWorkspaceVO();
                workspaceVO.setCoordinates(values.get(0).toString());
                workspaceVO.setObjectid(Integer.parseInt(values.get(1).toString()));
                //workspaceVO.setId(values.get(2).toString());
                workspaceVO.setName(values.get(3).toString());
                workspaceVO.setTime(values.get(4).toString());
                workspaceVO.setWxqgk(values.get(5).toString());
                workspaceVO.setCsdzzh(values.get(6).toString());
                workspaceVO.setYjczyd(values.get(7).toString());
                workspaceVO.setAllreport(values.get(8).toString());
                workspaceVO.setShapeLeng(Double.parseDouble(values.get(9).toString()));
                workspaceVO.setShapeArea(values.get(10).toString());
                workspaceVOs.add(workspaceVO);
            }
            // 批量新增
            this.saveData(workspaceVOs);
            return returnMsg.append("导入成功条数"+workspaceVOs.size()).toString();
        }catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            if(e.getMessage()==null){
                returnMsg.append("上传失败:请确保上传四种文件格式包含.shp,.dbf,.prj,.shx").toString();
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

}
